﻿using Kinlo.Entitys;
using MaterialDesignThemes.Wpf;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using UIWindows.Commands;
using UIWindows.Domains;
using UIWindows.Enums;
using UIWindows.GlobalStatics;
using UIWindows.Models.ParameterModels;
using UIWindows.Tools.Helper;
using XingLucifer.IBase.Enums;
using Microsoft.Win32;
using UIWindows.Models.Devices;
using System.Reflection;

namespace UIWindows.ViewModels.MesParameterItems
{

    public class MesRunParameterViewModel : ViewModelBase
    {
        MesParameterStatic _parameterStatic;
        public UserConfigStatic UserConfig { get; set; }
        public string SearchText { get; set; } = string.Empty;
        /// <summary>
        /// 界面展示
        /// </summary>
        public ObservableCollection<MesRunParameterModel> MesRunParameters { get; set; } = new ObservableCollection<MesRunParameterModel>();
        /// <summary>
        /// 取的原始集合
        /// </summary>
        public ObservableCollection<string> RunParameterSendTypeEmuns { get; set; } = new ObservableCollection<string>();
        /// <summary>
        /// 搜索后保留集合
        /// </summary>
        public ObservableCollection<string> SearchRunParameterSendTypeEmuns { get; set; } = new ObservableCollection<string>();
        public MesRunParameterViewModel(GlobalStatics.MesParameterStatic MESParameter, UserConfigStatic userConfig)
        {
            _parameterStatic = MESParameter;
            UserConfig = userConfig;
            MesRunParameters = new ObservableCollection<MesRunParameterModel>(ConversionHelper.CopyList(MESParameter.MesRunParameters));
            RunParameterSendTypeEmuns.Add("None");
            SearchRunParameterSendTypeEmuns.Add("None");
            RunParameterSendTypeEmuns.Add("PLC");
            SearchRunParameterSendTypeEmuns.Add("PLC");
            foreach (PropertyInfo property in typeof(RangeParameterModel).GetProperties())
            {
                var attribute = property.GetCustomAttribute<System.ComponentModel.DescriptionAttribute>();
                if (attribute != null)
                {
                    RunParameterSendTypeEmuns.Add(attribute.Description);
                    SearchRunParameterSendTypeEmuns.Add(attribute.Description);
                }
            }
            foreach (PropertyInfo property in typeof(RJ6902CAGXParametersModel).GetProperties())
            {
                var attribute = property.GetCustomAttribute<System.ComponentModel.DescriptionAttribute>();
                if (attribute != null)
                {
                    RunParameterSendTypeEmuns.Add(attribute.Description);
                    SearchRunParameterSendTypeEmuns.Add(attribute.Description);
                }
            }

            //var enums = Enum.GetValues(typeof(RunParameterSendTypeEmun))
            //    .OfType<RunParameterSendTypeEmun>().ToList()
            //    .Select(x => x.ToString());
            //RunParameterSendTypeEmuns = new ObservableCollection<string>(enums);
            //SearchRunParameterSendTypeEmuns = new ObservableCollection<string>(enums);
        }

        public DelegateCommand<string> SendSearchTextCMD => new DelegateCommand<string>(str =>
        {
            SearchText = str;
        });
        public DelegateCommand ExportCMD => new DelegateCommand(() =>
        {

        });
        public DelegateCommand ImportCMD => new DelegateCommand(() =>
        {
            try
            {
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Multiselect = false;//该值确定是否可以选择多个文件
                dialog.Title = "请选择文件";
                dialog.Filter = "Excel 工作簿(*.xls)|*.xls";
                var v = dialog.ShowDialog();
                if (v == true)
                {
                    string filePath = dialog.FileName;
                    var excelResult = ExportHelper.ImproExcel<MesRunParameterModel>(filePath);
                    excelResult.ToList().ForEach(x =>
                    {
                        x.ID = MesRunParameters.Count + 1;
                        MesRunParameters.Add(x);
                    });
                }
            }
            catch (Exception)
            {


            }

        });
        /// <summary>
        /// 对比本地属性，如果对不上就清空
        /// </summary>
        public DelegateCommand ContrastCMD => new DelegateCommand(async () =>
        {
            List<string> errMegs = new List<string>();
            foreach (var item in MesRunParameters)
            {
                if (!RunParameterSendTypeEmuns.Any(x => x == item.SendType.ToString()))
                {
                    errMegs.Add(item.SendType.ToString());
                    item.SendType = string.Empty ; 
                }
            }
            if (errMegs.Count > 0)
            {
                await $"注意：{string.Join(",", errMegs)} 本地无此属性，已清空属性及特性列，请删除或重新选择！".MessageDialogs(MessageLevelType.警告, true, Enums.PopUpTypes.Global, Visibility.Visible);

            }
            else
            {
                MyMessageQueue.Enqueue("所有属性对比无错！", "知道啦", () => { });
            }
        });

        public DelegateCommand CreateCMD => new DelegateCommand(() =>
        {
            MesRunParameters.Add(new MesRunParameterModel
            {
                ID = MesRunParameters.Count + 1
            });
        });
        public DelegateCommand<DataGrid> RemoveCMD => new DelegateCommand<DataGrid>(data =>
        {
            try
            {
                int count = data.SelectedItems.Count;
                for (int i = count - 1; i > -1; i--)
                {
                    var ret = data.SelectedItems[i] as MesRunParameterModel;
                    if (ret == null) { continue; }
                    var r = MesRunParameters.FirstOrDefault(x => x.ID == ret.ID);
                    if (r != null)
                    {
                        MesRunParameters.Remove(r);
                        for (int y = 0; y < MesRunParameters.Count; y++)
                        {
                            MesRunParameters[y].ID = y + 1;
                        }
                    }
                }

            }
            catch (Exception)
            {


            }

        });
        public SnackbarMessageQueue MyMessageQueue { get; set; } = new SnackbarMessageQueue(new TimeSpan(0, 0, 3));
        public DelegateCommand SaveCMD => new DelegateCommand(async () =>
        {

            var bl = (string)await "确定修改？".MessageDialogs(MessageLevelType.警告, true, Enums.PopUpTypes.Global, Visibility.Visible);
            if (bl == "true")
            {
                _parameterStatic.MesRunParameters = new ObservableCollection<MesRunParameterModel>(ConversionHelper.CopyList(MesRunParameters));
                _parameterStatic.Save();
                $"用户：[{UserConfig.LoginUser.Name}] 修改成功！".OperationLog(MessageLevelType.成功);
                MyMessageQueue.Enqueue("修改成功！", "知道啦", () => { });
            }


        });

        public DelegateCommand SearchCMD => new DelegateCommand(() =>
        {
            SearchRunParameterSendTypeEmuns = new ObservableCollection<string>(RunParameterSendTypeEmuns.Where(x => x.Contains(SearchText)));
        });

        public DelegateCommand<List<object>> SelectTextCMD => new DelegateCommand<List<object>>(arr =>
        {
            if (arr != null && arr.Count >= 2)
            {
                string str = arr[0].ToString();
                MesRunParameterModel mesRunParameterModel = arr[1] as MesRunParameterModel;
                mesRunParameterModel.SendType = str;
                // mesRunParameterModel.SendType =(RunParameterSendTypeEmun)Enum.Parse(typeof(RunParameterSendTypeEmun), str);
            }
        });
    }
}
